import {
  Component
} from '@angular/core';
import {
  NavController,
  NavParams,
  LoadingController,
  ViewController,
  ToastController,
  Platform,
  Events
} from 'ionic-angular';
import {
  TabsPage
} from "../tabs/tabs";
import {
  RegisterPage
} from "../register/register";
import {
  FindPage
} from '../find/find';
import {
  baseCommon
} from '../../common/baseCommon';
import {
  Http,
  Headers,
  RequestOptions,
  URLSearchParams
} from '@angular/http';
import {
  Md5
} from "ts-md5/dist/md5";
import {
  AppConfig
} from './../../app/app.config';
import {
  Storage
} from '@ionic/storage'
import {
  Geolocation
} from '@ionic-native/geolocation'
import Dexie from "dexie";
import {GroupsUtil} from '../../common/CommonUtil'

/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */


@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  phone: any;
  password: any;
  latitude: any; //维度
  longitude: any; //经度
  version: any;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public http: Http,
              public event: Events,
              public loadingCtrl: LoadingController,
              public viewCtrl: ViewController,
              public toastCtrl: ToastController,
              public storage: Storage,
              private platform: Platform,
              public geolocation: Geolocation) {

  }

  ionViewDidLoad() {
    this.geolocation.getCurrentPosition().then((resp) => {
      this.latitude = resp.coords.latitude;
      this.longitude = resp.coords.longitude;
      this.storage.set('x', this.longitude);
      this.storage.set('y', this.latitude);
    }).catch((error) => {
      alert('位置信息有误！');
      console.log('Error getting location', error);
    });

    this.storage.get('version').then(val => {
      if (val == null) {
        this.storage.set('version', 1)
        this.version = 1;
      } else {
        this.version = val;
      }
    })


  }

  login() {
    if (this.phone == '' || this.password == '') {
      baseCommon.showToast(this.toastCtrl, '手机号或者密码不能为空....')
    } else {
      this.getLoginMes(AppConfig.httpLoc + '/login', this.phone, this.password);
    }
  }

  register() {
    this.navCtrl.push(RegisterPage);
  }

  find() {
    this.navCtrl.push(FindPage)
  }

  /**
   * 登录
   * @param 2018-3-28 孙嘉宁
   * @param {any} apiUrl
   * @param {any} phone
   * @param {any} password
   * @returns
   * @memberof RestProvider
   */
  getLoginMes(apiUrl, phone, password) {
    var loading = baseCommon.showLoading(this.loadingCtrl, "登录中...");
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });

    let pramas: URLSearchParams = new URLSearchParams();

    pramas.set('realPhone', phone);
    pramas.set('password', Md5.hashStr(password).toString());
    pramas.set('x', this.longitude);
    pramas.set('y', this.latitude);

    let getData: any;

    this.http.post(apiUrl, pramas, options)
      .toPromise()
      .then(data => {
        loading.dismiss();
        getData = data.json();
        if (getData.message == "成功") {
          this.storage.set('status', 'logined');
          this.storage.set('phone', getData.data[1])
          this.storage.set('realPhone', phone);
          this.storage.set('password', Md5.hashStr(password).toString());
          this.storage.set('sessionID', getData.data[0]);
          // this.init(this.storage,phone);
          this.connect(this.storage, phone);
          // this.storage.set('sessionID', getData.data[0]);
          // super.getInfo(this.http,getData.data[1],getData.data[0]);
          AppConfig.socket = io.connect(AppConfig.socketLoc);
          var event = this.event;

          AppConfig.socket.on('connect', () => {
            console.log("Client has connected to the server!");
            this.auth(getData.data[0]);
          });
          AppConfig.socket.on('message', data => {
            var nowGroupID = data.groupID;
            if (AppConfig.groups != null) {
              GroupsUtil.update(nowGroupID);
            }
            event.publish('message.received', data, Date.now());
            // console.log("发送成功!");
          });

          AppConfig.socket.on('disconnect', () => {
            console.log("The client has disconnected!");
          });
          let headers = new Headers({
            'Content-Type': 'application/x-www-form-urlencoded',
          });

          let options = new RequestOptions({
            headers: headers,
          });

          this.http.get(AppConfig.httpLoc + '/info/' + getData.data[1] + "?sessionID=" + getData.data[0], options)
            .toPromise()
            .then(data => {
              this.storage.set('nickname', data.json().data.nickname);
              this.storage.set('userImg', data.json().data.imageURL);
            }, err => {
              console.log(err);
            })

          this.navCtrl.push(TabsPage)
        } else {
          baseCommon.showToast(this.toastCtrl, "手机号或者密码输入错误！")
        }
      }, err => {
        console.log(err);
      })
  }

  /**
   * 关闭当前页面的方法
   *
   * @memberof LoginPage
   */
  dismiss() {
    this.viewCtrl.dismiss();
  }


  connect(storage: Storage, phone: string) {
    // console.log(typeof this.phone)
    AppConfig.db = new Dexie(phone);
    AppConfig.db.version(1).stores({
      message: '++msgID,groupID,phone,username,date'
    });
  }

  /**
   * 验证身份
   * @param sessionID
   */
  auth(sessionID) {
    console.log('进行了身份验证')
    var jsonObject = {
      message: sessionID
    };
    AppConfig.socket.emit('auth', jsonObject);
  }
}
